import "./associatedUsers.scss";
import React, { useEffect, useRef, useState } from "react";
import {
  Table,
  Button,
  Input,
  Select,
  DrawerProps,
  Drawer,
  Form,
  Modal,
  Checkbox,
  Breadcrumb,
  Divider,
  FormInstance,
  message,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import {
  SearchOutlined,
  CloseOutlined,
  DoubleLeftOutlined,
  MinusCircleOutlined,
  PlusCircleOutlined,
} from "@ant-design/icons";
import type { CheckboxValueType } from "antd/es/checkbox/Group";
import axios from "../../../../utils/http";

// 关联用户

// 组件
const AssociatedUsers = () => {
  //数据总数
  const [total, setTotal] = useState();
  //渲染数据
  const getUser = () => {
    axios({
      url: "/associatedget",
      params: {
        search: "",
      },
    }).then((res: { [propName: string]: any }) => {
      console.log(res);
      if (res.error == 0) {
        // console.log(res.data);
        let _data = res.data.map((v: { key_a: number }) => {
          return { ...v, key: v.key_a };
        });
        setTotal(res.total);
        setData(_data);
      }
    });
  };

  //获取角色导航的数据
  const getAllRole = () => {
    axios({
      url: "/getAllRole",
      method: "post",
    }).then((res: { [propName: string]: any }) => {
      console.log(res, "getAllRole");
      if (res.error == 0) {
        //map 会返回一个新的数组
        let _data = res.data.map((v: { id: number }) => {
          return { ...v };
        });
        setAllRole(_data);
        let _content = res.content.map((v: { id: number }) => {
          return { ...v };
        });
        setAllRoleContent(_content);
      }
    });
  };

  useEffect(() => {
    getUser();
    getAllRole();
  }, []);

  //重现写左侧导航
  interface roleContents {
    id: number;
    roleContent: string;
  }
  const [allRole, setAllRole] = useState<roleContents[]>([]);
  const [allRoleContent, setAllRoleContent] = useState<roleContents[]>([]);
  //导航 删除
  //删除角色的数据
  const roleNavEdit = (ev: any, id: number) => {
    console.log(ev, id, "title");
    let _roleContent = ev.slice(0, ev.lastIndexOf("、"));
    console.log(_roleContent);
    axios({
      url: "/delRoleData",
      method: "post",
      data: {
        roleContent: _roleContent,
        id: id,
      },
    }).then((res: { [propName: string]: any }) => {
      console.log(res);
      if (res.error == 0) {
        getAllRole();
      }
    });
  };

  //添加角色
  //添加弹窗的标题
  const [addRoleNavTitle, setAddRoleNavTitle] = useState<string>();
  const [roleNavAddShow, setRoleNavShow] = useState(false);
  const [addInputForm] = Form.useForm();
  //输入的content
  const [content, setContent] = useState();
  const roleNavAdd = (ev: any, content: any) => {
    setRoleNavShow(true);
    // let text: string = ev;
    setAddRoleNavTitle(ev);
    setContent(content);
    addInputForm.setFieldsValue({ roleName: "" });
  };
  //添加里的确定
  const ensureAddRoleNav = () => {
    setRoleNavShow(false);
    let addInput = addInputForm.getFieldsValue(true);
    let _roleContent = content + "、" + addInput.roleName;
    // console.log(_roleContent,"_roleContent");
    axios({
      url: "/addRoleData",
      method: "post",
      data: {
        roleContent: _roleContent,
        roleTitle: addRoleNavTitle,
      },
    }).then((res: { [propName: string]: any }) => {
      console.log(res);
      if (res.error == 0) {
        getAllRole();
      }
    });
  };

  //li上的点击事件
  const oLiClick = (ev: string) => {
    console.log(ev, "ev");
    axios({
      url:"/oLiClick",
      method:"post",
      data:{
        roleName:ev
      }
    }).then((res: { [propName: string]: any })=>{
      if(res.error==0){
        let _data = res.data.map((v: { key_a: number }) => {
          return { ...v, key: v.key_a };
        });
        setData(_data);
      }
    })
  };

  //重现写左侧导航完

  //搜索
  const [searchForm] = Form.useForm();
  const searchRole = (search: any) => {
    if (search.name.trim() == "") {
      getUser();
    } else {
      let _data = data.filter((v: { username: string }) => {
        return v.username.includes(search.name);
      });
      setData(_data);
    }
  };

  //重置
  const reset = () => {
    searchForm.setFieldsValue({ name: "" });
    getUser();
  };

  //高级筛选
  const [open, setOpen] = useState(false);
  const senior = () => {
    if (open == false) {
      setOpen(true);
    } else {
      setOpen(false);
    }
  };
  const [placement, setPlacement] = useState<DrawerProps["placement"]>("top");
  const advancedFilter = (search: any) => {
    axios({
      url: "/advancedFilter",
      method: "post",
      data: {
        nickname: search.nickname || "",
        username: search.username || "",
        address: search.address || "",
        roleType: search.roleType || "",
      },
    }).then((res: { [propName: string]: any }) => {
      if (res.error == 0) {
        let _data = res.data.map((v: { key_a: number }) => {
          return { ...v, key: v.key_a };
        });
        setData(_data);
      }
    });
    setOpen(false);
  };
  //高级筛选完

  //编辑弹窗
  interface options {
    label: string;
    value: string;
  }

  const [editOpen, setEditOpen] = useState(false);
  const [options1, setOptions1] = useState<options[]>([]);
  const [options2, setOptions2] = useState<options[]>([]);
  const [options3, setOptions3] = useState<options[]>([]);
  let _options1 = new Array();
  let _options2 = new Array();
  let _options3 = new Array();

  const getOptions = () => {
    console.log(allRole, "allRole");
    for (let i = 0; i < allRole.length; i++) {
      if (i == 0) {
        _options1 = allRole[0].roleContent.split("、");
      } else if (i == 1) {
        _options2 = allRole[1].roleContent.split("、");
      } else {
        _options3 = allRole[2].roleContent.split("、");
      }
    }
    // console.log(_options1, _options2, _options3, "_options1");
    let _data1: options[] = _options1.map((v) => {
      return { label: v, value: v };
    });
    console.log(_data1, "_data1");
    setOptions1(_data1);
    let _data2: options[] = _options2.map((v) => {
      return { label: v, value: v };
    });
    console.log(_data2, "_data2");
    setOptions2(_data2);
    let _data3: options[] = _options3.map((v) => {
      return { label: v, value: v };
    });
    console.log(_data3, "_data3");
    setOptions3(_data3);
    console.log(options1, options2, options3, "options3");
  };

  //点击编辑按钮时，赋初始值
  const [systemRoleEdit, setSystemRoleEdit] = useState<[string]>([""]);
  const [institutionRolesEdit, setInstitutionRolesEdit] = useState<[string]>([
    "",
  ]);
  const [salesPersonasEdit, setSalesPersonasEdit] = useState<[string]>([""]);
  const [systemRoleDisabled, setSys] = useState(true);
  const [institutionRolesDisabled, setInst] = useState(true);
  const [salesPersonasDisabled, setSale] = useState(true);
  const [editId, setEditId] = useState();
  const editShow = () => {
    //判断是否选中
    if (selData.length > 0 && selData != null) {
      //赋初始值
      let _roleType: any;
      let _roleName: any;
      selData.map((v: { [propName: string]: any }) => {
        _roleType = v.roleType;
        _roleName = v.roleName;
        console.log(v.key);
        setEditId(v.key);
        getOptions();
      });
      let _data = _roleName.split("、");
      if (_roleType == "系统角色") {
        setSys(false);
        _data.map((v: string) => {
          systemRoleEdit.push(v);
        });
      } else if (_roleType == "机构角色") {
        setInst(false);
        _data.map((v: string) => {
          institutionRolesEdit.push(v);
        });
      } else if (_roleType == "销售角色") {
        setSale(false);
        _data.map((v: string) => {
          salesPersonasEdit.push(v);
        });
      }
      setEditOpen(true);
    } else {
      message.error("请选择要编辑的角色");
    }
  };

  const editShowCancel = () => {
    systemRoleEdit.splice(0);
    institutionRolesEdit.splice(0);
    salesPersonasEdit.splice(0);
    setSys(true);
    setInst(true);
    setSale(true);
    setEditOpen(false);
  };
  //当选择时
  const [selEdit, setSelEdit] = useState([]);
  const onChange = (checkedValues: any) => {
    console.log("checked = ", checkedValues);
    setSelEdit(checkedValues);
  };

  const editShowOk = () => {
    let _okData = selEdit.join("、");
    // console.log(editId, "hdhdhddh");

    axios({
      url: "/associatEdit",
      method: "post",
      data: {
        key_a: editId,
        roleName: _okData,
      },
    }).then((res: { [propName: string]: any }) => {
      if (res.error == 0) {
        getUser();
        message.success("编辑成功");
      }
    });
    setEditOpen(false);
  };
  //编辑弹窗完

  //删除弹窗
  //选择了哪些数据
  const [selData, setSelData] = useState([]);
  const [DeltOpen, setDelOpen] = useState(false);

  const delShow = () => {
    if (selData.length > 0 && selData != null) {
      setDelOpen(true);
      console.log(selData, "opopopop");
    } else {
      message.error("请选择要删除的角色");
    }
  };
  //删除里的确定
  let key: any;
  const ensureDel = () => {
    selData.map((v: { [propName: string]: any }) => {
      key = v.key_a;
    });
    axios({
      url: "/associatdel",
      method: "post",
      data: {
        key: key,
      },
    }).then((res: { [propName: string]: any }) => {
      if (res.error == 0) {
        getUser();
      }
    });
    setDelOpen(false);
  };
  //删除弹窗完

  //表格的
  interface DataType {
    key: React.Key;
    nickname: string;
    name: string;
    address: string;
    roleType: string;
    roleName: string;
  }
  const columns: ColumnsType<DataType> = [
    {
      title: "用户名",
      dataIndex: "nickname",
    },
    {
      title: "姓名",
      dataIndex: "username",
    },
    {
      title: "所属机构",
      dataIndex: "address",
    },
    {
      title: "角色类型",
      dataIndex: "roleType",
    },
    {
      title: "角色名称",
      dataIndex: "roleName",
    },
  ];
  const [data, setData] = useState([]);
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
      console.log(`selectedRowKeys`, selectedRows);
      setSelData(selectedRows);
    },
  };
  //表格完
  // 分页
  const pagination = {
    defaultPageSize: 5,
    defaultCurrent: 1,
    total: data.length,
    showQuickJumper: true,
    showSizeChanger: true,
    pageSizeOptions: [5, 10, 15, 20],
  };
  //分页完
  return (
    <div className="associatedUsers">
      <div className="title">
        <Breadcrumb separator=">">
          <Breadcrumb.Item>角色管理</Breadcrumb.Item>
          <Breadcrumb.Item href="">关联用户</Breadcrumb.Item>
        </Breadcrumb>
      </div>
      <Divider />
      <div className="content">
        <div className="content-left">
          <div className="total-role" onClick={reset}>
            全部角色<span>{total}</span>
          </div>
          <div>
            {allRole.map((v1: { [propName: string]: any }) => {
              return (
                <span key={v1.id}>
                  <div className="title-role">
                    {v1.roleTitle}
                    <span className="total-icon">
                      <MinusCircleOutlined
                        className="icon"
                        onClick={() => {
                          roleNavEdit(v1.roleContent, v1.id);
                        }}
                      />
                      <PlusCircleOutlined
                        onClick={() => {
                          roleNavAdd(v1.roleTitle, v1.roleContent);
                        }}
                      />
                    </span>
                  </div>
                  <ul>
                    {allRoleContent[v1.id - 1].roleContent
                      .split("、")
                      .map((v: any, i: number) => {
                        return (
                          <li
                            key={i}
                            onClick={() => {
                              oLiClick(v);
                            }}
                          >
                            {v}
                          </li>
                        );
                      })}
                  </ul>
                </span>
              );
            })}
          </div>
          {/* 添加导航角色 */}
          <Modal
            title={addRoleNavTitle}
            centered
            open={roleNavAddShow}
            onOk={ensureAddRoleNav}
            onCancel={() => setRoleNavShow(false)}
            className="edit-show"
          >
            <Form
              form={addInputForm}
              labelCol={{
                span: 4,
              }}
              autoComplete="off"
            >
              <Form.Item
                label="角色名称"
                name="roleName"
                rules={[
                  {
                    required: true,
                    message: "请输入角色名称",
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Form>
          </Modal>
        </div>
        <div className="content-right">
          <div className="action">
            <Form
              className="search"
              layout="inline"
              onFinish={searchRole}
              style={{ alignItems: "center" }}
              form={searchForm}
            >
              <Form.Item>
                <Button
                  type="primary"
                  style={{ background: "#69657e", marginLeft: "0px" }}
                  onClick={editShow}
                >
                  编辑
                </Button>
              </Form.Item>
              <Form.Item>
                <Button
                  type="primary"
                  style={{ background: "#69657e" }}
                  onClick={delShow}
                >
                  删除
                </Button>
              </Form.Item>
              <Form.Item name="name">
                <Input
                  placeholder="请输入姓名"
                  style={{ width: "220px", marginLeft: "150px" }}
                />
              </Form.Item>
              <Form.Item>
                <Button
                  type="primary"
                  style={{ background: "#69657e" }}
                  icon={<SearchOutlined />}
                  htmlType="submit"
                >
                  搜索
                </Button>
              </Form.Item>
              <Form.Item>
                <Button
                  type="primary"
                  style={{ background: "#69657e" }}
                  onClick={reset}
                >
                  重置
                </Button>
              </Form.Item>
              <Divider
                type="vertical"
                className="ver"
                style={{ width: "5px", height: "20px" }}
              />
              {/* 高级筛选 */}
              <Form.Item>
                <Button
                  type="link"
                  style={{ color: "#52a6ff" }}
                  onClick={senior}
                >
                  高级筛选
                  <DoubleLeftOutlined
                    rotate={270}
                    style={{ color: "#d6d6d6" }}
                  />
                </Button>
              </Form.Item>
            </Form>
          </div>
          {/* 高级筛选弹框 */}
          <div className="site-drawer-render-in-current-wrapper">
            <Drawer
              placement={placement}
              closable={false}
              onClose={() => {
                setOpen(false);
              }}
              open={open}
              key={placement}
              getContainer={false}
              height={180}
            >
              <div
                className="seniorClose"
                onClick={() => {
                  setOpen(false);
                }}
              >
                <CloseOutlined />
              </div>
              <Form
                className="senior"
                layout="inline"
                onFinish={advancedFilter}
              >
                <Form.Item label="用户名" name="nickname">
                  <Input placeholder="请输入用户名" />
                </Form.Item>
                <Form.Item label="姓名" name="username">
                  <Input placeholder="请输入姓名" />
                </Form.Item>
                <Form.Item label="所属机构" name="address">
                  <Input placeholder="请输入所属机构" />
                </Form.Item>
                <Form.Item label="角色类型" name="roleType">
                  <Select style={{ width: 180 }} placeholder="请选择">
                    <Select.Option value="系统角色">系统角色</Select.Option>
                    <Select.Option value="机构角色">机构角色</Select.Option>
                    <Select.Option value="销售角色">销售角色</Select.Option>
                  </Select>
                </Form.Item>

                <div className="seniorBtn">
                  <Form.Item>
                    <Button
                      type="primary"
                      style={{ background: "#69657e" }}
                      icon={<SearchOutlined />}
                      htmlType="submit"
                    >
                      查询
                    </Button>
                  </Form.Item>
                  <Form.Item>
                    <Button
                      type="primary"
                      style={{ background: "#69657e" }}
                      onClick={() => {
                        setOpen(false);
                      }}
                    >
                      取消
                    </Button>
                  </Form.Item>
                </div>
              </Form>
            </Drawer>
          </div>
          {/* 编辑弹窗 */}
          <Modal
            title="编辑用户角色"
            centered
            open={editOpen}
            onOk={editShowOk}
            onCancel={editShowCancel}
            className="edit-show"
          >
            <div
              style={{
                display: "flex",
                marginTop: "15px",
                marginBottom: "10px",
              }}
            >
              <p style={{ marginRight: "10px" }}>系统角色</p>
              <Checkbox.Group
                options={options1}
                defaultValue={systemRoleEdit}
                onChange={onChange}
                disabled={systemRoleDisabled}
              />
            </div>
            <div
              style={{
                display: "flex",
                marginTop: "10px",
                marginBottom: "10px",
              }}
            >
              <p style={{ marginRight: "10px" }}>机构角色</p>
              <Checkbox.Group
                options={options2}
                defaultValue={institutionRolesEdit}
                onChange={onChange}
                disabled={institutionRolesDisabled}
              />
            </div>
            <div
              style={{
                display: "flex",
                marginTop: "10px",
                marginBottom: "10px",
              }}
            >
              <p style={{ marginRight: "10px" }}>销售角色</p>
              <Checkbox.Group
                options={options3}
                defaultValue={salesPersonasEdit}
                onChange={onChange}
                disabled={salesPersonasDisabled}
              />
            </div>
          </Modal>
          {/* 删除弹窗 */}
          <Modal
            title="提示"
            centered
            open={DeltOpen}
            onOk={ensureDel}
            onCancel={() => setDelOpen(false)}
          >
            <p>确定要删除该用户的角色？</p>
          </Modal>

          <Table
            rowSelection={{
              type: "radio",
              ...rowSelection,
            }}
            bordered
            columns={columns}
            dataSource={data}
            pagination={pagination}
          />
        </div>
      </div>
    </div>
  );
};

export default AssociatedUsers;
